<template>
  <view class="used-car-page">
    <!-- 搜索区域 -->
    <view class="search-container">
      <view class="search-box">
        <u-icon name="search" size="28" color="#999" class="search-icon"></u-icon>
        <input 
          type="text" 
          v-model="searchKey" 
          placeholder="输入车辆的名称或品牌" 
          class="search-input"
          @confirm="handleSearch"
        />
        <button class="search-btn" @click="handleSearch">搜索</button>
      </view>
    </view>
	
	<!-- 遮罩层 -->
	<view class="mask" v-if="showMask" @click="closeAllDropdown"></view>
	<!-- 筛选区域 -->
	<view class="filter-container">
	  <!-- 默认排序 -->
	  <view 
	    class="filter-item" 
	    @click="toggleSortDropdown"
	    :class="{ 'active': activeFilter === 'sort' }"
	  >
	  <view class="filter-btn-group">
	    <text class="filter-btn">{{ selectedSort }}</text>
	    <view 
		  class="custom-arrow" 
		  :class="{ 'rotate': showSortDropdown }"
		></view>
	  </view>
	    <!-- 排序下拉框 -->
	    <view class="dropdown-menu" v-if="showSortDropdown">
	      <view 
	        class="dropdown-item" 
	        v-for="(option, index) in sortOptions" 
	        :key="index" 
	        @click.stop="selectSort(option)"
	      >
	        {{ option }}
	      </view>
	    </view>
	  </view>
	  <!-- 品牌 -->
	  <view 
	    class="filter-item" 
	    @click="toggleBrandDropdown"
	    :class="{ 'active': activeFilter === 'brand' }"
	  >
	  <view class="filter-btn-group">
	    <text class="filter-btn">{{ selectedBrand }}</text>
	    <view 
		  class="custom-arrow" 
		  :class="{ 'rotate': showBrandDropdown }"
		></view>
	  </view>
	    <!-- 品牌下拉框（示例，需替换为实际品牌数据） -->
	    <view class="dropdown-menu" v-if="showBrandDropdown">
	      <view 
			class="dropdown-item" 
			v-for="(option, index) in brandOptions" 
			:key="index" 
			@click.stop="selectBrand(option)"
		  >
			{{ option }}
		  </view>
	    </view>
	  </view>
	  <!-- 价格（类似品牌，可扩展） -->
	  <view 
		class="filter-item" 
		@click="togglePriceDropdown"
		:class="{ 'active': activeFilter === 'price' }"
	  >
	  <view class="filter-btn-group">
		<text class="filter-btn">{{ selectedPrice }}</text>
		<view 
			  class="custom-arrow" 
			  :class="{ 'rotate': showPriceDropdown }"
			></view>
	  </view>
		<!-- 品牌下拉框（示例，需替换为实际品牌数据） -->
		<view class="dropdown-menu" v-if="showPriceDropdown">
		  <view 
			class="dropdown-item" 
			v-for="(option, index) in priceOptions" 
			:key="index" 
			@click.stop="selectPrice(option)"
		  >
			{{ option }}
		  </view>
		</view>
	  </view>
	  <!-- 更多筛选 -->
	  <view class="filter-item">
	    <text class="filter-btn">更多筛选</text>
	  </view>
	</view>

    <!-- 车辆列表区域 -->
    <view class="car-list">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <u-loading-icon size="30" color="#007aff"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态或列表内容 -->
      <view v-else>
        <!-- 空状态 -->
        <view v-if="carList.length === 0" class="empty-state">
          <text class="empty-text">暂无车辆数据</text>
        </view>

        <!-- 列表内容 -->
        <view v-else>
          <view class="car-item" v-for="(car, index) in carList" :key="car.carId || index" @click="goToDetail(index)"
          >
            <image class="car-img" :src="getFirstImage(car.image)" mode="aspectFill"
              lazy-load v-if="car.image"/>
            <view class="car-img placeholder-img" v-else></view>
            
            <view class="car-info">
              <view class="car-name">{{ car.brandName }}</view>
              <view class="car-meta">
                <text>{{ car.licenseDate }} / {{ car.mileage }}万公里</text>
              </view>
			  <view class="car-price">
			    <text>{{ car.price }} 元</text>
			  </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getUsedCars } from '@/api/usedcar/usedcar.js';
import { listTypeList } from '@/api/series/series.js';

export default {
  data() {
    return {
      searchKey: '',
      carList: [],
      loading: false,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
	  showMask: false, // 控制遮罩显示
	  showSortDropdown: false, // 控制排序下拉显示
	  showBrandDropdown: false, // 控制品牌下拉显示
	  showPriceDropdown: false, // 控制价格下拉显示
	  activeFilter: '', // 当前激活的筛选项（默认“默认排序”）
	  sortOptions: ['默认排序', '最新上架', '车程最短', '里程最少', '价格最高', '价格最低'], // 排序选项
	  selectedSort: '默认排序', // 当前选中的排序
	  brandOptions: [], 
	  selectedBrand: '全部品牌',
	  priceOptions: ['不限价格', '2万以下', '2-5万', '5-10万', '10-15万', '15万以上'], // 排序选项
	  selectedPrice: '不限价格' // 当前选中的排序
    };
  },
  onLoad() {
    this.fetchCarData(true);
	// 调用接口获取品牌列表
	  listTypeList().then(res => {
	    if (res.code === 200) {
			// 先创建一个新数组，第一个元素为“全部品牌”
			this.brandOptions = ['全部品牌'];
			// 再将接口返回的品牌数据（string 集合）依次添加到新数组中
			res.rows.forEach(brandName => {
			  this.brandOptions.push(brandName);
			});
	    } else {
	      this.$u.toast('获取品牌数据失败');
	    }
	  }).catch(err => {
	    console.error('获取品牌数据出错:', err);
	    this.$u.toast('网络错误，请稍后重试');
	  });
  },
  onReachBottom() {
    if (!this.loading && this.hasMore) {
      this.fetchCarData();
    }
  },
  methods: {
    fetchCarData(isRefresh = false) {
      if (isRefresh) {
        this.pageNum = 1;
        this.carList = [];
        this.hasMore = true;
      }

      if (!this.hasMore) return;

      this.loading = true;

      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        brandName: this.searchKey.trim(),
		sortType: this.selectedSort,
		brandType: this.selectedBrand,
		priceType: this.selectedPrice
      };

      getUsedCars(params)
        .then(res => {
          this.loading = false;
          if (res.code === 200) {
            const newData = res.rows;
            this.carList = [...this.carList, ...newData];
            this.pageNum++;
            this.hasMore = newData.length >= this.pageSize;
          } else {
            this.$u.toast(res.msg || '获取数据失败');
          }
        })
        .catch(err => {
          this.loading = false;
          console.error('获取车辆数据失败:', err);
          this.$u.toast('网络错误，请稍后重试');
        });
    },
    handleSearch() {
      this.fetchCarData(true);
    },
    goToDetail(index) {
		const car = this.carList[index]; // 从列表里直接取当前项
		const id = car.carId;
		  if (id) {
			uni.navigateTo({
			  url: `/pages/work/usedcar/detail?carId=${id}`
			});
		  }
    },
	// 提取第一个图片地址
	getFirstImage(imageStr) {
	  if (imageStr) {
		// 按逗号分隔，取第一个
		return imageStr.split(',')[0];
	  }
	  return '';
	},
	// 切换排序下拉显示
	  toggleSortDropdown() {
		this.showSortDropdown = !this.showSortDropdown;
		this.showBrandDropdown = false; // 关闭品牌下拉
		this.showPriceDropdown = false; // 关闭价格下拉
		this.activeFilter = this.showSortDropdown ? 'sort' : '';
		this.showMask = this.showSortDropdown; // 显示/隐藏遮罩
	  },
	  // 切换品牌下拉显示
	  toggleBrandDropdown() {
		this.showBrandDropdown = !this.showBrandDropdown;
		this.showSortDropdown = false; // 关闭排序下拉
		this.showPriceDropdown = false; // 关闭价格下拉
		this.showMask = this.showBrandDropdown; // 显示/隐藏遮罩
		this.activeFilter = this.showBrandDropdown ? 'brand' : '';
	  },
	  // 切换价格下拉显示
	  togglePriceDropdown() {
		this.showPriceDropdown = !this.showPriceDropdown;
		this.showSortDropdown = false; // 关闭排序下拉
		this.showBrandDropdown = false; // 关闭排序下拉
		this.showMask = this.showPriceDropdown; // 显示/隐藏遮罩
		this.activeFilter = this.showPriceDropdown ? 'price' : '';
	  },
	  // 关闭所有下拉框和遮罩
	    closeAllDropdown() {
	      this.showSortDropdown = false;
	      this.showBrandDropdown = false;
		  this.showPriceDropdown = false;
	      this.showMask = false;
	    },
	  // 选择排序选项
	  selectSort(sort) {
	    this.selectedSort = sort;
		this.closeAllDropdown(); // 调用关闭方法
		this.fetchCarData(true); // 调用接口刷新列表接口刷新列表
	  },
	  // 选择品牌选项（示例，需根据实际品牌数据调整）
	  selectBrand(brand) {
		this.selectedBrand = brand;
	    this.closeAllDropdown(); // 调用关闭方法
		this.fetchCarData(true); // 调用接口刷新列表
	  },
	  // 选择价格选项（示例，需根据实际品牌数据调整）
	  selectPrice(price) {
		this.selectedPrice = price;
	    this.closeAllDropdown(); // 调用关闭方法
		this.fetchCarData(true); // 调用接口刷新列表
	  }
  }
};
</script>

<style scoped>
.used-car-page {
  padding: 16rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.search-container {
  margin-bottom: 20rpx;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 60rpx;
  padding: 0 20rpx;
  height: 76rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.search-icon {
  margin-right: 10rpx;
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: 28rpx;
  color: #333;
}

.search-btn {
  background-color: #007aff;
  color: #fff;
  border-radius: 40rpx;
  padding: 0 24rpx;
  height: 56rpx;
  font-size: 28rpx;
  line-height: 56rpx;
}

.car-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.loading-state {
  padding: 80rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
}

.loading-text {
  font-size: 28rpx;
  margin-top: 20rpx;
}

.empty-state {
  padding: 120rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
}

.empty-text {
  font-size: 28rpx;
  margin-top: 20rpx;
}

.car-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  display: flex;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.car-img {
  width: 200rpx;
  height: 150rpx;
  border-radius: 8rpx;
}

.placeholder-img {
  width: 200rpx;
  height: 150rpx;
  border-radius: 8rpx;
  background-color: #f5f5f5;
}

.car-info {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.car-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.car-meta {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
}
.car-price {
  font-size: 24rpx;
  color: palevioletred;
  margin-top: 10rpx;
}
/* 筛选区域样式 */
.filter-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: #fff;
  padding: 16rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.filter-item {
  position: relative;
  flex: 1;
  text-align: center;
}

.filter-btn {
  padding: 12rpx;
  font-size: 26rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 激活态样式 */
.filter-item.active .filter-btn {
  background-color: #ffe6cc; /* 示例激活背景色 */
  border-color: #ff9933; /* 示例激活边框色 */
}
.filter-btn-group {
  display: flex;  /* 水平布局 */
  align-items: center;  /* 垂直居中 */
  justify-content: center;  /* 水平居中 */
}
.arrow-icon {
  margin-left: 8rpx;  /* 图标和文字之间的间距 */
  transition: transform 0.3s ease;  /* 箭头旋转过渡动画 */
}


/* 自定义实心向下箭头（CSS三角） */
.custom-arrow {
  width: 0;
  height: 0;
  border-left: 8rpx solid transparent;
  border-right: 8rpx solid transparent;
  border-top: 12rpx solid #333; /* 实心向下箭头（三角方向由border决定） */
  margin-left: 4rpx;
  transition: transform 0.2s ease;
}

/* 箭头旋转类：展开时朝上 */
.custom-arrow.rotate {
  transform: rotate(180deg);
}

/* 遮罩层样式 */
.mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3); /* 半透明黑色 */
  z-index: 998; /* 遮罩层级低于下拉框 */
}

/* 下拉框样式（确保层级高于遮罩） */
.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 8rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  z-index: 999; /* 高于遮罩 */
}

/* 下拉项自适应宽度 */
.dropdown-item {
  padding: 12rpx;
  font-size: 24rpx;
  text-align: center;
  border: 1px solid #eee;
  border-radius: 8rpx;
  margin: 4rpx;
  flex: 0 0 calc(33.33% - 8rpx); /* 一行显示 3 个（可根据需求调整） */
}

.dropdown-item:last-child {
  border-bottom: none;
}
</style>